#coding=utf-8
#LightCam 进程启动程序

import multiprocessing,subprocess
import socket,os,time,re,sys
import lc_libs


def func(ProcessName):
	
	#定义命令
	comd="ps -ef|grep -w '"+str(ProcessName)+"'|grep -v 'grep'|awk '{if ( $3 == 1 ) print $0}'"
	
	#执行命令
	popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

	#等待命令执行完毕
	while True:
		if popen.poll()==None:
			time.sleep(0.01)
			continue
		else:
			break
			
	#获取命令执行结果
	line=popen.stdout.read().strip("\n").strip("\r").split()
	
	if len(line)>0:
		return True
	else:
		return False


if __name__ == "__main__":

	length = len(sys.argv)
	if length<2:
		strs="wrong para,please input a para."
		print strs
		exit(0)

	agent_hostname=lc_libs.lc_gethostname()

	CurrentConf=[]
	
	for line in open("../conf/lc_status.conf"):
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		CurrentConf.append(line)
				
	tag=0
	
	if sys.argv[1] == "All":
		StartCommand=''
		for line in CurrentConf:
			lines=line.strip('\n\r').split('\t')
			ProcessName = lines[1]
			if ProcessName == "MongoDB":
				StartCommand = lines[3]
			#StartCommand="cd $LIGHTCAM_HOME/mongodb;rm -f data/mongod.lock;./bin/mongod --fork --dbpath data --logpath mongo.log --logappend --nojournal > /dev/null"
		res=func("mongod")
		if res:
			print 'MongoDB is already started.'
		else:
			print 'Starting MongoDB ...'
			os.system(StartCommand)
			time.sleep(10)
			print 'MongoDB has been started.'
		
		for line in CurrentConf:
			lines=line.strip('\n\r').split('\t')
			Hostname = lines[0]
			ProcessName = lines[1]
			ScriptsName = lines[2]
			StartCommand = lines[3]
			if ProcessName != "MongoDB":
				if func(ScriptsName):
					print ProcessName + ' is already started.'
					continue
				print "Starting "+ProcessName + '...'
				os.system(StartCommand)
				time.sleep(0.1)
				print ProcessName + ' has been started.'
				tag=1
		exit(0)
	
	for line in CurrentConf:
		lines=line.strip('\n\r').split('\t')
		Hostname = lines[0]
		ProcessName = lines[1]
		ScriptsName = lines[2]
		StartCommand = lines[3]
		if ProcessName in sys.argv:
			if func(ScriptsName):
				print ProcessName + ' is already started.'
				continue
			print "Starting "+ProcessName + '...'
			os.system(StartCommand)
			time.sleep(1)
			print ProcessName + ' has been started.'
			tag=1
			
	if tag==0:
		print "Nothing to do. Exiting..."
